package com.fooddiary.web;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.fooddiary.service.IEatingService;
import com.fooddiary.service.IModelService;
import com.fooddiary.web.form.EatingForm;

/**
 * 
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Controller
public class EatingController extends AbstractController{

	private final String EATING_FORM_KEY = "eatingForm";
	private final String EDITEATING_URL = "/private/editeating";
	private final String REDIRECT_URL = "redirect:/private/weight/initEditWeight.action";
	private final String EATING_TYPES = "eatingTypes";
	
	private final String INIT_EATING_ACTION = "/private/eating/initEditEating.action";
	private final String SAVE_EATING_ACTION = "/private/eating/saveEating.action";
	
	@Autowired
	IModelService modelService;
	
	@Autowired
	IEatingService eatingService;
	
	@RequestMapping(value=INIT_EATING_ACTION, method=RequestMethod.GET)
	public ModelAndView initEatingForm(
			@RequestParam (value = "id", required = false) Integer id,
			@RequestParam (value = "weightId", required = false) Integer weightId){
		ModelAndView mv = null;
		try{
			mv = new ModelAndView(EDITEATING_URL);
			mv.addObject( EATING_FORM_KEY, eatingService.initEatingForm(id, weightId) );
			mv.addObject( EATING_TYPES, eatingService.fillEatingTypesList() );
		}catch (Exception err) {
			EatingForm eatingForm = new EatingForm();
			eatingForm.getErrors().add( err.getMessage() );
			mv=new ModelAndView(ERROR_URL);
			mv.addObject( EATING_FORM_KEY, eatingForm );
		}
		return mv;
	}
	
	@RequestMapping(value=SAVE_EATING_ACTION, method=RequestMethod.POST)
	public ModelAndView submitEatingForm(@ModelAttribute(EATING_FORM_KEY) EatingForm form,
			BindingResult result, SessionStatus status){
		ModelAndView mv = null;
		try {
			eatingService.saveEatingForm( modelService.getModel(), form );
			if(CollectionUtils.isEmpty( form.getErrors() )){
				mv = new ModelAndView( REDIRECT_URL+"?id="+form.getWeightId() );
			}else{
				mv = new ModelAndView( EDITEATING_URL );
				mv.addObject( EATING_FORM_KEY, form );
				mv.addObject( EATING_TYPES, eatingService.fillEatingTypesList() );
			}
		} catch ( Exception err ) {
			mv = new ModelAndView( ERROR_URL );
		}
		return mv;
	}
}
